package nextgen
import grails.converters.XML

class RestController {
	def buildRdfService
	
	def list= {
		render nextgen.Resource.list() as XML
    }
	
	def insert= {
		def resource= nextgen.Resource.findByUrl(params['resource'].url)
		if (resource) {
			if (params.resource.brief) { resource.brief= params.resource.brief }
			if (params.resource.technical) { resource.technical= params.resource.technical }
			if (params.resource.payload) { resource.payload= params.resource.payload }
			resource.save()
		}
		else {
			resource= new nextgen.Resource()
			resource.url= params.resource.url
			resource.brief= params.resource.brief
			resource.technical= params.resource.technical
			resource.payload= params.resource.payload
			resource.save()
		}
		if (!resource.hasErrors()) { 
			render resource as XML 
			buildRdfService.buildRdfNt()
			buildRdfService.buildRdfJson()
		}
		else { render resource.errors as XML}
	}
	
	def delete= {
		def webService= nextgen.Resource.get(params['resource'].id)
		if (webService) {
			webService.delete()
			response.status= 204
		}
		else { SentNotFoundResponse() }
	}
	
	def deleteAll= {
		nextgen.Resource.list().each { r ->
			r.delete()
		}
	}
	
	def show= {
		def resource= Resource.get(params.id)
		if (!resource) { response.status= 404 }
		else { render resource as XML }
	}
	def showRdfNt= {
		def provisions= new File('web-app/resources/provisions.nt').text
		render provisions
	}
	def showRdfJson= {
		def provisions= new File('web-app/resources/provisions.json').text
		render provisions
	}
}
